#ifndef __UDSF_SYSTICK_C__
#define __UDSF_SYSTICK_C__

#include "app.h"

/*
*   notice:
*   UDSF 同UDF编程：不可调用cstd-lib,只可调用"sdk_ifs_udk_cfg.h"、"sys_api.h"中列出的API函数。
*   UDSF文件内函数均需使用static修饰符，且UDF中以#include "udsf_xxx.c"形式引用
*/
#include "udsf_sys_api.c"

static void udsf_systick_init(uint8_t is_xip,uint8_t ms) __attribute__((unused));
static void udsf_systick_deinit(void) __attribute__((unused));

#define SYSTICK_EN()     (SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk)

static void udsf_NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
  if(IRQn < 0) {
    SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
  else {
    NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
}
static void udsf_systick_init(uint8_t is_xip,uint8_t ms){
	if( is_xip ){
		SysTick->LOAD = XIP_SYS_CLK/1000*ms;
	}else{
		SysTick->LOAD = ROM_SYS_CLK/1000*ms;
	}
	SysTick->VAL  = 0;
	udsf_NVIC_SetPriority(SysTick_IRQn,3);
	SYSTICK_EN();
	NVIC->ISER[0] = (1ul << ((uint32_t)(SysTick_IRQn) & 0x1F));
}

static void udsf_systick_deinit(void){
	SysTick->CTRL = 0;
	NVIC->ICER[0] = (1ul << ((uint32_t)(SysTick_IRQn) & 0x1F));
}

#endif
